#include "WebsocketRequest.h"


#if defined(WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include <Winsock2.h>
#include <WS2tcpip.h>
#include <ws2bth.h>
#endif

#if defined(LINUX)
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <stdio.h>
#include "WebSocketProtocol.h"
#include <qdebug.h>

enum WebSocketOpCode {
    ContinuationFrame = 0x0,
    TextFrame 	  = 0x1,
    BinaryFrame 	  = 0x2,
    ConnectionClose   = 0x8,
    Ping 		  = 0x9,
    Pong 		  = 0xA
};

WebsocketRequest::WebsocketRequest()
{
}

WebsocketRequest::~WebsocketRequest()
{

}
int  WebsocketRequest::process(int fd, char *buf, unsigned int maxsize, bool b_conn)
{
	WebSocketProtocol cp;
	cp.decode(buf, maxsize);


    if (cp.opcode() == WebSocketOpCode::ContinuationFrame)
    {
         qDebug()<< "	continuation frame" ;
    }
    else if (cp.opcode() == WebSocketOpCode::TextFrame)
    {
         qDebug()<< "	text frame" ;
    }
    else if (cp.opcode() == WebSocketOpCode::BinaryFrame)
    {
        qDebug()<< "	binary frame" ;
    }
    else if (cp.opcode() == WebSocketOpCode::ConnectionClose)
    {
         qDebug()<< "	connection close" ;
         return -5;
    }
    else if (cp.opcode() == WebSocketOpCode::Ping)
    {
        qDebug()<< "	ping" ;
    }
    else if (cp.opcode() == WebSocketOpCode::Pong)
    {
        qDebug()<< "	pong" ;
    }
    else
    {
        qDebug()<< "	opcode not handled by application" ;
    }

    //if (cp.opcode() != 0x1)
    //    return -2;

	int nreads = cp.payload_length();

	char buf1[1024] = {0};
	strncpy(buf1, cp.payload_data(), nreads);
	buf1[nreads] = '\0';

	printf("payload %s\n", buf1);
	return 0;
}


